#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include "Log.hpp"
#include "InetAddr.hpp"


const std::string default_dict_path = "./dictionary.txt";
const std::string sep = ": ";

using namespace LogModule;

class Dict
{
public:
    Dict(const std::string &path = default_dict_path) : _dict_path(path)
    {}
    
    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "open dictnary: " << _dict_path << " error";
        }
        LOG(LogLevel::DEBUG) << "open dictnary: " << _dict_path << " success";
        std::string line;
        while(std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "parse word error: " << line;
                continue;
            }
            std::string en = line.substr(0, pos);
            std::string cn = line.substr(pos + sep.size());
            if(en.empty() || cn.empty())
            {
                LOG(LogLevel::WARNING) << "Illegal dictionary content";
                continue;
            }
            _dict.insert({en, cn});
            //LOG(LogLevel::DEBUG) << "load: " << line;
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string& word, InetAddr& client)
    {
        auto iter = _dict.find(word); 
        if(iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "Enter the translation module, [" << client.Ip() << " : " << client.Port() << "]# " << word << " -> None";
            return "None";
        }

        //LOG(LogLevel::DEBUG) << "find kv: " << iter->first << ": " << iter->second; 
        LOG(LogLevel::DEBUG) << "Enter the translation module, [" << client.Ip() << " : " << client.Port() << "]# " << word << " -> " << iter->second;

        return iter->second;

    }


    ~Dict()
    {}
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};
